package com.im.server.enterprise.common.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.im.base.common.util.KeyUtil;
import com.im.server.enterprise.business.push.DepartmentChatPush;
import com.im.server.enterprise.common.bean.DepartmentChatContent;
import com.im.server.enterprise.common.bean.DepartmentChatItem;
import com.im.server.enterprise.common.dao.DepartmentChatDAO;
import com.im.server.enterprise.common.dao.DepartmentDAO;
import com.im.server.enterprise.common.dao.DepartmentMemberDAO;
import com.im.server.enterprise.common.manager.DepartmentMemberManager;
import com.im.server.general.common.dao.UserDAO;
import com.im.server.general.common.data.ChatItem;
import com.im.server.general.common.service.api.WordsFilterBaseService;
import com.onlyxiahui.im.message.data.UserData;
import com.onlyxiahui.im.message.data.chat.Content;
import com.onlyxiahui.im.message.data.chat.Item;
import com.onlyxiahui.im.message.data.chat.Section;

/**
 * @author XiaHui
 * @date 2017年8月13日 上午10:00:16
 */
@Service
public class DepartmentChatService {

	protected final Logger logger = LogManager.getLogger(this.getClass());

	@Resource
	WordsFilterBaseService wordsFilterBaseService;
	@Resource
	DepartmentChatPush departmentChatPush;
	@Resource
	UserDAO userDAO;
	@Resource
	DepartmentMemberDAO departmentMemberDAO;
	@Resource
	DepartmentChatDAO departmentChatDAO;
	@Resource
	DepartmentDAO departmentDAO;
	@Resource
	DepartmentMemberManager departmentMemberManager;

	@Transactional
	public void departmentChat(String key, String userId, String departmentId, Content content) {
		List<ChatItem> chatItemList = wordsFilter(content);
		long timestamp = content.getTimestamp();
		UserData userData = userDAO.getUserDataById(userId);
		if (null == userData) {
			userData = new UserData();
			userData.setId(userId);
		}
		pushDepartmentChat(key, userId, departmentId, content);
		addDepartmentChatLog(userData, key, departmentId, chatItemList, timestamp);
	}

	public void pushDepartmentChat(String key, String userId, String departmentId, Content content) {
		List<String> userIdList = departmentMemberManager.getDepartmentMemberIdList(departmentId);
		if(null!=userIdList){
			departmentChatPush.pushDepartmentChat(key, departmentId, userId, content, userIdList);
		}
	}

	private List<ChatItem> wordsFilter(Content content) {
		content.setTimestamp(System.currentTimeMillis());
		List<ChatItem> chatItemList = new ArrayList<ChatItem>();

		List<Section> sections = content.getSections();

		if (null != sections) {
			int sectionsSize = sections.size();
			for (int i = 0; i < sectionsSize; i++) {
				Section section = sections.get(i);
				List<Item> items = section.getItems();
				if (null != items) {
					int itemsSize = items.size();
					for (int j = 0; j < itemsSize; j++) {
						ChatItem chatItem = new ChatItem();

						Item item = items.get(j);
						String type = item.getType();
						String value = item.getValue();

						chatItem.setType(type);
						chatItem.setValue(value);
						chatItem.setSection(i);
						chatItem.setRank(j);

						if (Item.type_text.equals(type)) {
							value = wordsFilterBaseService.wordsFilter(value);
							item.setValue(value);
							chatItem.setFilterValue(value);
						} else {
							chatItem.setFilterValue(value);
						}
						chatItemList.add(chatItem);
					}
				}
			}
		}
		return chatItemList;
	}

	/**
	 * 记录聊天室的聊天内容
	 * 
	 * @author: XiaHui
	 * @createDate: 2016年8月19日 下午3:26:10
	 * @update: XiaHui
	 * @updateDate: 2016年8月19日 下午3:26:10
	 */
	@Transactional
	private void addDepartmentChatLog(UserData userData, String messageId, String departmentId, List<ChatItem> chatItemList, long timestamp) {
		messageId = (null == messageId || "".equals(messageId)) ? KeyUtil.getKey() : messageId;
		if (null != userData) {
			DepartmentChatContent content = createDepartmentChatContent(messageId, departmentId, userData, timestamp);
			departmentChatDAO.save(content);
			List<DepartmentChatItem> list = new ArrayList<DepartmentChatItem>();
			for (ChatItem item : chatItemList) {
				DepartmentChatItem chatLog = new DepartmentChatItem();
				chatLog.setMessageId(messageId);
				chatLog.setDepartmentChatContentId(content.getId());
				chatLog.setDepartmentId(content.getDepartmentId());
				chatLog.setUserId(content.getUserId());
				chatLog.setRank(item.getRank());
				chatLog.setSection(item.getSection());
				chatLog.setType(item.getType());
				chatLog.setValue(item.getValue());
				chatLog.setFilterValue(item.getFilterValue());
				list.add(chatLog);
			}
			departmentChatDAO.saveList(list);
		}
	}

	private DepartmentChatContent createDepartmentChatContent(String messageId, String departmentId, UserData userData, long timestamp) {
		DepartmentChatContent chatLog = new DepartmentChatContent();
		chatLog.setMessageId(messageId);
		chatLog.setDepartmentId(departmentId);
		chatLog.setDepartmentName("");
		chatLog.setTime(new Timestamp(timestamp));
		chatLog.setTimestamp(timestamp);
		chatLog.setUserHead(userData.getHead());
		chatLog.setUserId(userData.getId());
		chatLog.setUserName(userData.getName());
		chatLog.setUserNickname(userData.getNickname());
		chatLog.setUserRemark("");
		chatLog.setIsSend("1");
		return chatLog;
	}
}